<template>
	<view class="edit-profile-page">
		<view class="profile-pic-container">
			<u-upload :fileList="fileList" :maxCount="1" :previewFullImage="true" width="90" height="90" shape="circle"
				name="1" ref="uUpload" accept="image" @afterRead="handleImageUpload" @delete="deletePic">
				<!-- This slot is shown if fileList is empty -->
				<view class="empty-slot-upload">
					<u-icon name="camera" color="#AEAEAE" size="35"></u-icon>
				</view>
			</u-upload>
		</view>

		<u--form labelPosition="left" :model="model1" :rules="rules" labelWidth="70" ref="uForm" class="profile-form">
			<!-- Nickname Block -->
			<u-form-item label="昵称" prop="userInfo.nickName" ref="itemNickName"
				class="form-item-radius standalone-item">
				<u--input v-model="model1.userInfo.nickName" :placeholder="model1.userInfo.nickName ? '' : '请填写昵称'"
					border="none" inputAlign="right"></u--input>
			</u-form-item>

			<!-- Personal Info Block -->
			<view class="form-block">
				<u-form-item label="性别" prop="userInfo.sex" @click="showSex = true;" ref="itemSex">
					<view class="input-display-value"
						:class="{'placeholder-value': !model1.userInfo.sex && model1.userInfo.sex !==0}">
						{{ model1.userInfo.sex === 0 ? '男' : (model1.userInfo.sex === 1 ? '女' : '未设置') }}
					</view>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>

				<u-form-item label="身高" prop="userInfo.height" ref="itemHeight">
					<u--input v-model="model1.userInfo.height" :placeholder="model1.userInfo.height ? '' : '请填写身高'"
						border="none" inputAlign="right"></u--input>
				</u-form-item>

				<u-form-item label="生日" prop="userInfo.birthday" ref="itemBirthday">
					<picker mode="date" fields="day" class="input-display-value"
						:class="{'placeholder-value': !model1.userInfo.birthday}" :value="model1.userInfo.birthday"
						@change="bindDateChange">
						<view class="birthday-input" v-if="!model1.userInfo.birthday">
							<text>请选择你的生日</text>
						</view>
						<view class="birthday-input birthday" v-else>
							{{model1.userInfo.birthday}}
						</view>
					</picker>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>

				<u-form-item label="星座" prop="userInfo.starsign" ref="itemStarsign">
					<u--input v-model="model1.userInfo.starsign" disabled disabledColor="#ffffff"
						:placeholder="model1.userInfo.starsign ? '' : '未设置'" border="none"
						inputAlign="right"></u--input>
				</u-form-item>

				<u-form-item label="学校" ref="itemSchoolHeader" @click="toggleSchoolDetails">
					<view slot="right">
						<u-icon :name="showSchoolDetails ? 'arrow-up' : 'arrow-down'" size="16"
							color="#303133"></u-icon>
					</view>
				</u-form-item>

				<template v-if="showSchoolDetails">
					<u-form-item label="小学" prop="userInfo.primarySchool" labelWidth="70" ref="itemElementary"
						class="sub-item">
						<u--input v-model="model1.userInfo.primarySchool"
							:placeholder="model1.userInfo.primarySchool ? '' : '未设置'" border="none"
							inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="中学" prop="userInfo.middleSchool" labelWidth="70" ref="itemMiddle"
						class="sub-item">
						<u--input v-model="model1.userInfo.middleSchool"
							:placeholder="model1.userInfo.middleSchool ? '' : '未设置'" border="none"
							inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="大学" prop="userInfo.school" labelWidth="70" ref="itemElementary"
						class="sub-item">
						<u--input v-model="model1.userInfo.school" :placeholder="model1.userInfo.school ? '' : '未设置'"
							border="none" inputAlign="right"></u--input>
					</u-form-item>
				</template>
			</view>

			<!-- Location & Career Block -->
			<view class="form-block">
				<u-form-item label="老家" prop="userInfo.hometown" ref="itemHometown">
					<u--input v-model="model1.userInfo.hometown" :placeholder="model1.userInfo.hometown ? '' : '请填写老家'"
						border="none" inputAlign="right"></u--input>
				</u-form-item>

				<u-form-item label="居住地" prop="userInfo.address" ref="itemAddress">
					<u--input v-model="model1.userInfo.address" :placeholder="model1.userInfo.address ? '' : '请填写居住地'"
						border="none" inputAlign="right"></u--input>
				</u-form-item>

				<u-form-item label="职业" prop="userInfo.job" ref="itemJob">
					<u--input v-model="model1.userInfo.job" :placeholder="model1.userInfo.job ? '' : '请填写职业'"
						border="none" inputAlign="right"></u--input>
				</u-form-item>

				<u-form-item label="签名" prop="userInfo.des" ref="itemSignature" @click="navigateToEditBio">
					<u--input v-model="model1.userInfo.des" :placeholder="model1.userInfo.des ? '' : '请输入个性签名'"
						border="none" inputAlign="right" disabled disabledColor="#ffffff"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
			</view>
		</u--form>

		<view class="submit-button-container">
			<u-button type="primary" color="#ff9900" @click="submit">提交</u-button>
		</view>

		<!-- Pickers and Action Sheets -->
		<u-action-sheet :show="showSex" :actions="actions" title="请选择性别" @close="showSex = false" @select="sexSelect">
		</u-action-sheet>
	</view>
</template>

<script>
	import {
		getUserInfoUpdate,
		getQiniuToken,
		generateQiniuToken,
		revokeFile
	} from '@/request/api.js'; // Ensure this path is correct
	import * as qiniu from 'qiniu-js'
	import Base64 from 'base64-js';

	export default {
		data() {
			return {
				uploadToken: null,
				uploadKey: null,
				fileList: [],
				showSex: false,
				showSchoolDetails: false,
				// 添加一个新属性来存储初始数据
				initialModel1: {},
				// 用于标记是否正在通过提交按钮返回，以绕过 onBackPress 的检查
				isNavigatingAfterSubmit: false,
				model1: {
					userInfo: {
						avatar: '',
						nickName: '一只爱旅游的🐸',
						sex: 1,
						birthday: '',
						height: '165cm',
						starsign: '',
						school: '',
						primarySchool: '人民小学',
						middleSchool: '淮阴中学',
						hometown: '江苏淮安',
						address: '四川成都',
						job: '画家',
						des: '想做一个走遍山川的自由人...',
						area: '',
					},
				},
				actions: [{
						name: '男',
						sex: 0
					},
					{
						name: '女',
						sex: 1
					}
				],
				rules: {
					'userInfo.nickName': [{
						type: 'string',
						required: true,
						message: '请填写昵称',
						trigger: ['blur', 'change']
					}, {
						max: 10,
						message: "最大长度为10个字",
						trigger: "blur"
					}],
					'userInfo.sex': {
						type: 'number',
						required: true,
						message: '请选择男或女',
						trigger: ['blur', 'change']
					}, // Changed type to number to match model
					'userInfo.birthday': {
						type: 'string',
						required: false,
						message: '请选择生日',
						trigger: ['change']
					},
					'userInfo.height': [{
						type: 'string',
						required: true,
						message: '请填写身高（cm）',
						trigger: ['blur', 'change']
					}, {
						pattern: /^\d{2,3}(cm)?$/,
						message: '身高范围应为50-250cm',
						trigger: 'blur'
					}],
					'userInfo.school': [{
						type: 'string',
						required: false,
						message: '请填写学校名称',
						trigger: ['blur', 'change']
					}, {
						max: 15,
						message: "最大长度15字",
						trigger: "blur"
					}],
					'userInfo.primarySchool': [{
						type: 'string',
						required: false,
						message: '请填写小学名称',
						trigger: ['blur', 'change']
					}, {
						max: 15,
						message: "最大长度15字",
						trigger: "blur"
					}],
					'userInfo.middleSchool': [{
						type: 'string',
						required: false,
						message: '请填写中学名称',
						trigger: ['blur', 'change']
					}, {
						max: 15,
						message: "最大长度15字",
						trigger: "blur"
					}],
					'userInfo.hometown': [{
						type: 'string',
						required: true,
						message: '请填写老家',
						trigger: ['blur', 'change']
					}, {
						max: 10,
						message: "最大长度为10个字",
						trigger: "blur"
					}],
					'userInfo.address': [{
						type: 'string',
						required: true,
						message: '请填写居住地',
						trigger: ['blur', 'change']
					}, {
						max: 10,
						message: "最大长度为10个字",
						trigger: "blur"
					}],
					'userInfo.job': [{
						type: 'string',
						required: true,
						message: '请填写职业',
						trigger: ['blur', 'change']
					}, {
						max: 10,
						message: "最大长度为10个字",
						trigger: "blur"
					}],
					'userInfo.des': [{
						type: 'string',
						required: true,
						message: '个人签名不能为空',
						trigger: ['blur', 'change']
					}, {
						max: 30,
						message: "最大长度为30个字",
						trigger: "blur"
					}],
				},
				originalFilename: null
			};
		},
		watch: {

			'$store.state.userInfo': {
				handler(newUserInfo) {
					if (newUserInfo) {
						this.model1.userInfo.nickName = newUserInfo.nickName || '';
						this.model1.userInfo.sex = newUserInfo.sex == 0 ? 0 : (newUserInfo.sex == 1 ? 1 : 2);

						if (newUserInfo.birthday) {
							this.model1.userInfo.birthday = this.$u.timeFormat(newUserInfo.birthday, 'yyyy-mm-dd');
						} else {
							this.model1.userInfo.birthday = '';
						}

						this.model1.userInfo.height = newUserInfo.height ? `${newUserInfo.height}cm` : '';
						this.model1.userInfo.school = newUserInfo.school || '';
						this.model1.userInfo.primarySchool = newUserInfo.primarySchool || '';
						this.model1.userInfo.middleSchool = newUserInfo.middleSchool || '';
						this.model1.userInfo.hometown = newUserInfo.hometown || '';
						this.model1.userInfo.address = newUserInfo.address || '';
						this.model1.userInfo.job = newUserInfo.job || '';
						this.model1.userInfo.des = newUserInfo.des || '';

						if (this.model1.userInfo.birthday) {
							this.getZodiac();
						} else {
							this.model1.userInfo.starsign = '';
						}
					}
					// 关键：深度克隆一份初始数据
					this.initialModel1 = JSON.parse(JSON.stringify(this.model1));
				},
				immediate: true,
				deep: true
			},
			'$store.state.userInfo.avatar': {
				handler(newVal) {
					if (newVal) {
						if (!this.fileList.length || this.fileList[0].url !== newVal) {
							this.fileList = [{
								url: newVal
							}];
						}
						this.model1.userInfo.avatar = newVal;
					} else {
						this.fileList = [];
						this.model1.userInfo.avatar = '';
					}
					// 关键：头像变化也需要更新初始数据
					this.initialModel1.userInfo.avatar = this.model1.userInfo.avatar;
				},
				immediate: true
			},
		},
		created() {
			uni.$on('profileBioUpdated', this.handleProfileBioUpdate);
		},
		onUnload() {
			uni.$off('profileBioUpdated', this.handleProfileBioUpdate);
		},
		// 关键：拦截返回事件
		onBackPress(options) {
			// 检查标志位，如果为true，则直接允许返回
			if (this.isNavigatingAfterSubmit) {
				return false;
			}
			// 检查是否有未保存的修改
			if (!this.hasChanges()) {
				return false; // 没有修改，允许正常返回
			}

			// 有修改，弹出提示框
			uni.showModal({
				title: '提示',
				content: '您的资料已修改，是否保存？',
				success: (res) => {
					if (res.confirm) {
						// 用户点击"确定"，执行保存操作
						this.submit();
					} else if (res.cancel) {
						// 用户点击"取消"，直接返回
						this.isNavigatingAfterSubmit = true; // 设置标志位
						uni.navigateBack();
					}
				}
			});

			// 必须返回 true，阻止默认的返回行为，等待用户在Modal中的操作
			return true;
		},
		methods: {
			// 新增：检查数据是否有变动
			hasChanges() {
				return JSON.stringify(this.model1) !== JSON.stringify(this.initialModel1);
			},
			async handleImageUpload(event) {
				let lists = [].concat(event.file);
				let fileListLen = this.fileList.length;
				lists.map((item) => {
					if (this.fileList.length > 0 && fileListLen > 0) {
						this.fileList.splice(0, 1);
						fileListLen = 0;
					}
					this.fileList.push({
						...item,
						url: item.url,
						status: "uploading",
						message: "上传中",
					});
				});

				for (let i = 0; i < lists.length; i++) {
					console.log(lists);
					this.originalFilename = lists[i].name
					await this.generateQiniuToken()
					const uploadedUrl = await this.uploadFilePromise(lists[i].url);
					console.log("uploadedUrl", uploadedUrl);
					this.model1.userInfo.avatar = uploadedUrl;

					let item = this.fileList[fileListLen];
					let obj = {
						status: "success",
						message: "",
						url: uploadedUrl
					};
					this.fileList.splice(fileListLen, 1, Object.assign(item, obj));
					fileListLen++;
				}
			},
			generateQiniuToken() {
				return new Promise((resolve, reject) => {
					let params = {
						originalFilename: this.originalFilename,
						purpose: "avatar"
					}
					getQiniuToken(params).then(res => {
						this.uploadToken = res.data.data.token
						this.uploadKey = res.data.data.key
						resolve(true)
					})
				})
			},
			uploadFilePromise(fileUrl) {
				const uploadUrl = 'https://up.qiniup.com'; // 上传七牛云
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: uploadUrl,
						filePath: fileUrl,
						name: "file",
						formData: {
							token: this.uploadToken,
							key: this.uploadKey
						},
						success: (res) => {
							try {
								const data = JSON.parse(res.data);
								console.log("data", data);
								resolve(`${this.$store.state.ossBaseUrl}/${data.key}`); // 实际CDN域名
							} catch (e) {
								uni.$u.toast('上传响应解析错误');
								reject(new Error('Upload response parsing error'));
							}
						},
						fail: (err) => {
							uni.$u.toast('上传接口请求失败');
							reject(err);
						}
					});
				});
			},
			deletePic(event) {
				this.fileList.splice(event.index, 1);
				this.model1.userInfo.avatar = "";
			},
			sexSelect(e) {
				this.model1.userInfo.sex = e.sex;
				this.$refs.uForm.validateField('userInfo.sex');
			},
			submit() {
				if (!this.model1.userInfo.avatar) {
					uni.$u.toast('请上传头像');
					return;
				}
				let heightValue = this.model1.userInfo.height ? parseInt(this.model1.userInfo.height.replace('cm', '')) :
					null;

				let params = {
					userId: this.$store.state.userInfo.userId,
					nickName: this.model1.userInfo.nickName,
					sex: this.model1.userInfo.sex, // Already number 0 or 1
					avatar: this.model1.userInfo.avatar,
					des: this.model1.userInfo.des,
					address: this.model1.userInfo.address,
					birthday: this.model1.userInfo.birthday, // Already YYYY-MM-DD
					school: this.model1.userInfo.school.trim(),
					primarySchool: this.model1.userInfo.primarySchool,
					middleSchool: this.model1.userInfo.middleSchool,
					height: heightValue,
					hometown: this.model1.userInfo.hometown,
					starsign: this.model1.userInfo.starsign,
					job: this.model1.userInfo.job,
					email: ""
				};
				console.log("params=======", params);
				getUserInfoUpdate(params).then(res => {
					if (res.data.code == 500) {
						uni.$u.toast(res.data.msg);
					} else {
						uni.showToast({
							title: '资料修改成功',
							icon: 'success'
						});
						// this.$store.dispatch('updateUserInfoAction', params);
						setTimeout(() => {
							// 在导航返回前设置标志位
							this.isNavigatingAfterSubmit = true;
							uni.navigateBack();
						}, 1500);
					}
				}).catch(err => {
					uni.$u.toast('请求失败，请稍后再试');
					console.error("Update error", err);
				});
			},
			// 生日
			bindDateChange(e) {
				console.log(e);
				this.model1.userInfo.birthday = e.target.value;
				this.getZodiac()
			},
			formatter(type, value) {
				if (type === 'year') return `${value}年`;
				if (type === 'month') return `${value}月`;
				if (type === 'day') return `${value}日`;
				return value;
			},
			getZodiac() {
				if (!this.model1.userInfo.birthday) {
					this.model1.userInfo.starsign = "";
					return;
				}
				const date = new Date(this.model1.userInfo.birthday); // YYYY-MM-DD is parsable by Date constructor
				const month = date.getMonth() + 1;
				const day = date.getDate();
				const zodiacDates = [
					[1, 20, "摩羯座", "水瓶座"],
					[2, 19, "水瓶座", "双鱼座"],
					[3, 21, "双鱼座", "白羊座"],
					[4, 20, "白羊座", "金牛座"],
					[5, 21, "金牛座", "双子座"],
					[6, 22, "双子座", "巨蟹座"],
					[7, 23, "巨蟹座", "狮子座"],
					[8, 23, "狮子座", "处女座"],
					[9, 23, "处女座", "天秤座"],
					[10, 24, "天秤座", "天蝎座"],
					[11, 23, "天蝎座", "射手座"],
					[12, 22, "射手座", "摩羯座"]
				];
				if ((month === 12 && day >= 22) || (month === 1 && day <= 19)) {
					this.model1.userInfo.starsign = "摩羯座";
					return;
				}
				// Adjust for 0-indexed array access
				const zodiacRule = zodiacDates[month - 1];
				if (!zodiacRule) { // Should not happen if date is valid
					this.model1.userInfo.starsign = "";
					return;
				}
				const [, thresholdDay, zodiacBefore, zodiacAfter] = zodiacRule;
				this.model1.userInfo.starsign = day >= thresholdDay ? zodiacAfter : zodiacBefore;
			},
			toggleSchoolDetails() {
				this.showSchoolDetails = !this.showSchoolDetails;
			},
			navigateToEditBio() {
				uni.navigateTo({
					url: '/pages_sub/user/editProfile/editProfile?currentBio=' + encodeURIComponent(this.model1
						.userInfo.des || '')
				});
			},
			handleProfileBioUpdate(newBio) {
				this.model1.userInfo.des = newBio;
				this.$refs.uForm.validateField('userInfo.des');
			}
		},
		onReady() {
			// It's good practice to ensure rules are set after the form is ready.
			// If $refs.uForm might not be available immediately, consider nextTick.
			this.$nextTick(() => {
				if (this.$refs.uForm) {
					this.$refs.uForm.setRules(this.rules);
				}
			});

			if (this.$refs.datetimePicker) {
				this.$refs.datetimePicker.setFormatter(this.formatter);
			}
		},
	};
</script>
<style lang="scss">
	page {
		background-color: #F7F6FB;
	}

	.edit-profile-page {
		padding: 0 30rpx 30rpx 30rpx;
		display: flex;
		flex-direction: column;
	}

	.profile-pic-container {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 40rpx 0;
	}

	.empty-slot-upload {
		width: 100%;
		height: 100%;
		border-radius: 50%;
		background-color: #E9E8ED;
		display: flex;
		justify-content: center;
		align-items: center;
		border: 1px solid #D5D5D5;
	}

	::v-deep .u-upload__wrap__preview__image {
		border-radius: 50% !important;
	}

	.profile-form {}

	.form-block {
		background-color: #FFFFFF;
		border-radius: 20rpx;
		margin-bottom: 24rpx;
		overflow: hidden;
	}

	.standalone-item {
		background-color: #FFFFFF;
		border-radius: 20rpx;
		margin-bottom: 24rpx;
		overflow: hidden;
	}

	.u-form-item {
		background-color: #FFFFFF;
		padding: 0 30rpx;
		box-sizing: border-box;

		&:not(:last-child) {
			border-bottom: 1px solid #F0F0F0;
		}
	}

	.form-block .u-form-item:last-child,
	.standalone-item.u-form-item {
		border-bottom: none !important;
	}


	::v-deep .u-form-item__body {
		padding: 30rpx 0;
	}

	::v-deep .u-line {
		border: none !important;
	}

	::v-deep .u-form-item__body>.u-border-bottom {
		display: none !important;
	}


	.input-display-value {
		flex: 1;
		text-align: right;
		font-size: 28rpx;
		color: #303133;
		padding-right: 10rpx;

		&.placeholder-value {
			color: #909399;
		}
	}

	::v-deep .u-input--disabled .u-input__content__field-wrapper__field {
		color: #303133 !important;
	}

	::v-deep .u-input__content__field-wrapper__field {
		text-align: right !important;
	}

	.u-form-item picker .input-display-value {
		width: 100%;
	}


	.sub-item {
		::v-deep .u-form-item__body__left__content__label {
			color: #606266;
		}
	}

	.submit-button-container {
		margin-top: 40rpx;
		padding: 0 20rpx;
	}
</style>